package com.handpay.nocardpay.baselibrary.notification.view.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.notification.adapter.NoticeListAdapter;
import com.handpay.nocardpay.baselibrary.notification.model.bean.NoticeBody;
import com.handpay.nocardpay.baselibrary.notification.model.bean.UserNoticeBean;
import com.handpay.nocardpay.baselibrary.notification.presenter.NoticePresenterImpl;
import com.handpay.nocardpay.baselibrary.notification.push.NoticePushFactory;
import com.handpay.nocardpay.baselibrary.notification.view.INoticeListView;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;

import java.util.HashMap;
import java.util.List;

/**
 * Created by sxshi on 2017/8/9.
 */

public class NotificationFragment extends BaseFragment implements INoticeListView, NoticeListAdapter.OnItemClickListener {
    private SwipeRefreshLayout swipe_refresh_widget = null;
    private RecyclerView recycle = null;
    private NoticePresenterImpl noticePresenter = null;
    private LinearLayoutManager mLayoutManager = null;
    private NoticeListAdapter adapter = null;
    private Toolbar mToolbar;

    public static NotificationFragment newInstance() {
        Bundle args = new Bundle();
        NotificationFragment fragment = new NotificationFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_notification;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.mine_notice);
    }

    @Override
    public void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_bill_24px);
        initToolbar(mToolbar, true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _mActivity.finish();
            }
        });
        swipe_refresh_widget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        swipe_refresh_widget.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        recycle = (RecyclerView) view.findViewById(R.id.recycle);
        recycle.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(_mActivity);
        recycle.setLayoutManager(mLayoutManager);
        recycle.setItemAnimator(new DefaultItemAnimator());
        adapter = new NoticeListAdapter(_mActivity, this);
        recycle.addItemDecoration(new DividerItemDecoration(_mActivity,
                DividerItemDecoration.VERTICAL));
        recycle.setAdapter(adapter);
    }

    @Override
    public void initListener() {
        //设置刷新监听
        swipe_refresh_widget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                doGetNotices();
            }
        });
    }

    //获取数据
    private void doGetNotices() {
        String userId = AccountUtils.getUserId(_mActivity);
        HPLog.i(HPLog.LFP_TAG, "-userId 1:" + userId);
        if (TextUtils.isEmpty(userId))
            return;
        String lastUpdateTime = PreferenceManager.getInstance(_mActivity).getString(userId, "");
        HPLog.i(HPLog.LFP_TAG, "-userId lastUpdateTime 2:" + lastUpdateTime);

        if (TextUtils.isEmpty(lastUpdateTime)) {
            swipe_refresh_widget.setRefreshing(false);
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.CLIENTCHANNEL, NoCardPayConfig.CLIENTCHANNEL);
        params.put(BaseProtocolKey.UPDATETIME, lastUpdateTime);
        HPLog.i(HPLog.LFP_TAG, "get notices params :" + params.toString());
        noticePresenter.queryNotices(params, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        noticePresenter = new NoticePresenterImpl(this, _mActivity);
//        noticePresenter.queryNoticesfromDB(AccountUtils.getUserId(_mActivity));
        doGetNotices();
    }

    @Override
    public void showNoticesWithDB(List<NoticeBody> noticeBodies) {
        HPLog.i(HPLog.LFP_TAG, "showNoticesWithDB:" + noticeBodies != null ? noticeBodies.size() : "noticeBodies is null!");
        adapter.setData(noticeBodies);
        detectNewNotice();
    }

    //触发一次看看是否还有新消息
    private void detectNewNotice() {
        boolean flag = noticePresenter.isReadNotice(AccountUtils.getUserId(_mActivity));
        HPLog.i(HPLog.LFP_TAG, "detectNewNotice flag:" + flag);
        NoticePushFactory.with().doBroadCastNotice(flag);
    }

    @Override
    public void showNotices(UserNoticeBean userNoticeBean) {
        HPLog.i(HPLog.LFP_TAG, "UserNoticeBean:" + userNoticeBean != null ? userNoticeBean.toString() : "is null");
        swipe_refresh_widget.setRefreshing(false);
        String lastUpdateTime = userNoticeBean.getLastUpdateTime();
        String userId = AccountUtils.getUserId(_mActivity);
        PreferenceManager.getInstance(_mActivity).putString(userId, lastUpdateTime);
        if (userNoticeBean.getList() != null && userNoticeBean.getList().size() > 0) {
            for (NoticeBody noticeBody : userNoticeBean.getList()) {
                noticeBody.setUserId(userId);
                noticeBody.setLastUpdateTime(lastUpdateTime);
                noticePresenter.addNotice(noticeBody);
            }
        }
        noticePresenter.deleteNotice(userId,20);
        noticePresenter.queryNoticesfromDB(userId);
    }

    @Override
    public void onClick(View v, NoticeBody noticeBody) {
        if (noticeBody != null) {
            if (!noticeBody.isRead()) {
                noticeBody.setRead(true);
                if(noticePresenter!=null) {
                    noticePresenter.updateNotice(noticeBody);
                    noticePresenter.queryNoticesfromDB(AccountUtils.getUserId(_mActivity));
                }
            }
            detectNewNotice();
            Bundle bundle = new Bundle();
            bundle.putString("from", "NoticeActivity");
            bundle.putParcelable("noticeBody", noticeBody);
            start(NoticeDetailFragment.newInstance(bundle));
        }
    }

    @Override
    public void onLongClick(View v, final NoticeBody noticeBody) {
        if (noticeBody != null) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.tip), _mActivity.getString(R.string.notice_delete_tip), _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (noticePresenter != null) {
                        noticePresenter.deleteNotice(noticeBody);
                        noticePresenter.queryNoticesfromDB(AccountUtils.getUserId(_mActivity));
                    }
                    dialog.dismiss();
                }
            }, _mActivity.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideSoftInput();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        noticePresenter.onDestory();
    }
}
